package model

import (
	"database/sql/driver"
	"fmt"
	"time"
)

type LocalTime struct {
	time.Time
}

// MarshalJSON 实现json序列化接口
func (t LocalTime) MarshalJSON() ([]byte, error) {
	formatted := t.Format("2006-01-02 15:04:05")
	return []byte(`"` + formatted + `"`), nil
}

// UnmarshalJSON 实现json反序列化接口
func (t *LocalTime) UnmarshalJSON(data []byte) error {
	str := string(data)[1 : len(data)-1]
	parsed, err := time.ParseInLocation("2006-01-02 15:04:05", str, time.Local)
	if err != nil {
		return err
	}
	t.Time = parsed
	return nil
}

// Scan 实现 sql.Scanner 接口
func (t *LocalTime) Scan(v interface{}) error {
	if value, ok := v.(time.Time); ok {
		*t = LocalTime{Time: value}
		return nil
	}
	return fmt.Errorf("can not convert %v to LocalTime", v)
}

// Value 实现 driver.Valuer 接口
func (t LocalTime) Value() (driver.Value, error) {
	return t.Time, nil
}
